#include <Arduino.h>
#include <stm32f1xx_hal.h>
#include "main.h"

#define LED_PIN PA8

// 串口定义
HardwareSerial MySerial(PA10, PA9); // RX, TX
I2S_HandleTypeDef hi2s2;
DMA_HandleTypeDef hdma_spi2_rx;

UART_HandleTypeDef huart1;

// 添加接收缓冲区
#define AUDIO_BUFFER_SIZE 4
uint32_t audioBuffer[AUDIO_BUFFER_SIZE];
uint8_t dataReady = 0;

extern "C"
{

  void SystemClock_Config(void)
  {
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

    /** Initializes the RCC Oscillators according to the specified parameters
     * in the RCC_OscInitTypeDef structure.
     */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON;
    RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL4;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
      MyError_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
     */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
    {
      MyError_Handler();
    }
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2S2;
    PeriphClkInit.I2s2ClockSelection = RCC_I2S2CLKSOURCE_SYSCLK;
    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
    {
      MyError_Handler();
    }
  }

  /**
   * @brief I2S2 Initialization Function
   * @param None
   * @retval None
   */
  static void MX_I2S2_Init(void)
  {
    /* 使能GPIO时钟 */
    __HAL_RCC_GPIOB_CLK_ENABLE();

    /* 配置I2S2引脚 */
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    GPIO_InitStruct.Pin = GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_15;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    hi2s2.Instance = SPI2;
    hi2s2.Init.Mode = I2S_MODE_MASTER_RX;
    hi2s2.Init.Standard = I2S_STANDARD_PHILIPS;
    hi2s2.Init.DataFormat = I2S_DATAFORMAT_24B;
    hi2s2.Init.MCLKOutput = I2S_MCLKOUTPUT_DISABLE;
    hi2s2.Init.AudioFreq = I2S_AUDIOFREQ_8K;
    hi2s2.Init.CPOL = I2S_CPOL_LOW;
    if (HAL_I2S_Init(&hi2s2) != HAL_OK)
    {
      MyError_Handler();
    }
  }

  /**
   * @brief USART1 Initialization Function
   * @param None
   * @retval None
   */
  static void MX_USART1_UART_Init(void)
  {
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
      MyError_Handler();
    }
  }

  /**
   * Enable DMA controller clock
   */
  static void MX_DMA_Init(void)
  {
    /* DMA controller clock enable */
    __HAL_RCC_DMA1_CLK_ENABLE();

    /* DMA interrupt init */
    /* DMA1_Channel4_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel4_IRQn, 1, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel4_IRQn);

    /* 配置DMA句柄 */
    hdma_spi2_rx.Instance = DMA1_Channel4;
    hdma_spi2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_spi2_rx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_spi2_rx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_spi2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
    hdma_spi2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
    hdma_spi2_rx.Init.Mode = DMA_CIRCULAR;
    hdma_spi2_rx.Init.Priority = DMA_PRIORITY_HIGH;

    if (HAL_DMA_Init(&hdma_spi2_rx) != HAL_OK)
    {
      MyError_Handler();
    }

    __HAL_LINKDMA(&hi2s2, hdmarx, hdma_spi2_rx);
  }

  /**
   * @brief GPIO Initialization Function
   * @param None
   * @retval None
   */
  static void MX_GPIO_Init(void)
  {
    /* GPIO Ports Clock Enable */
    __HAL_RCC_GPIOD_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();

    /* 使能调试接口 */
    __HAL_RCC_AFIO_CLK_ENABLE();
    __HAL_AFIO_REMAP_SWJ_NOJTAG();
  }

  uint32_t val24;
  int val32;
  unsigned cb_cnt = 0;
  // I2S接收完成回调函数
  void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s)
  {
    if (hi2s == &hi2s2)
    {
      cb_cnt++; // 回调次数计数
      // 将两个32整型合并为一个
      // dat32 example: 0000fffb 00004f00
      val24 = (audioBuffer[0] << 8) + (audioBuffer[1] >> 8);
      // 将24位有符号整型扩展到32位
      if (val24 & 0x800000)
      { // negative
        val32 = 0xff000000 | val24;
      }
      else
      { // positive
        val32 = val24;
      }
      // 以采样频率的十分之一，串口发送采样值
    }
  }

  /**
   * @brief  This function is executed in case of error occurrence.
   * @retval None
   */
  void
  MyError_Handler(void)
  {
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
  }
}

void setup()
{
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MySerial.begin(115200);
  MySerial.println("Starting system initialization...");

  pinMode(LED_PIN, OUTPUT);
  MySerial.println("GPIO initialized");

  MX_DMA_Init();
  MySerial.println("DMA initialized");

  MX_I2S2_Init();
  MySerial.println("I2S initialized");

  // 启动I2S DMA接收
  MySerial.println("Starting I2S DMA receive...");
  HAL_I2S_Receive_DMA(&hi2s2, (uint16_t *)audioBuffer, 4);

  MySerial.println("System initialized");
}

// 在全局变量区域添加
uint32_t lastVolume = 0;

// 在全局区域添加音量计算函数
// 修改音量计算函数
uint32_t calculateVolume(uint32_t *buffer, uint16_t size)
{
  uint64_t sum = 0;
  for (uint16_t i = 0; i < size; i++)
  {
    // 对于24位数据，通常只需要使用高16位或适当移位处理
    // 根据实际情况调整移位位数
    int32_t sample = (int32_t)(buffer[i] >> 8) - 32768; // 取高16位并转换为有符号值
    sum += sample * sample;
  }
  return (uint32_t)sqrt((double)sum / size);
}

void loop()
{

  if (cb_cnt % 10 == 0)
  {
    MySerial.print(">1234:");
    MySerial.println(val32);
    // MySerial.println("\r\n");
  }
}